package com.rabbit.interceptor;

import com.alibaba.fastjson.JSON;
import com.rabbit.constant.ResultCodeEnum;
import com.rabbit.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * Created by zjw on 2022/3/20 9:24 上午
 */
@Slf4j
public class DemoInterceptor implements HandlerInterceptor {

    private List<String> patterns;

    public DemoInterceptor() {
        patterns = Arrays.asList("/add", "/delete", "/update", "/resetPassword", "/changeEnabled", "/updateAvatar", "/truncate", "/batchDelete");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        for (String pattern : patterns) {
            if (isMatch(pattern, path)) {
                ResultVO<Object> resultVO = new ResultVO<>(ResultCodeEnum.DEMO_EXCEPTION);
                response.setContentType("text/plain; charset=utf-8");
                response.getWriter().write(JSON.toJSONString(resultVO));
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private boolean isMatch(String pattern, String requestUri) {
        return requestUri.contains(pattern);
    }
}
